<template>
  <div class="trash-view">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <div class="title-section">
          <h2 class="page-title">
            <el-icon><Delete /></el-icon>
            {{ t('trash.title') }}
          </h2>
          <el-tag v-if="!statsLoading" type="info" size="small">
            {{ stats.totalFiles }} {{ t('trash.stats.totalFiles') }}
          </el-tag>
          <el-tag v-if="stats.expiringSoon > 0" type="warning" size="small">
            {{ stats.expiringSoon }} {{ t('trash.stats.expiringSoon') }}
          </el-tag>
        </div>
        
        <!-- 统计信息 -->
        <div v-if="!statsLoading" class="stats-info">
          <span class="stat-item">
            {{ t('trash.stats.totalSize') }}: {{ formatFileSize(stats.totalSize) }}
          </span>
          <span class="stat-item">
            {{ t('trash.stats.autoCleanup') }}
          </span>
        </div>
      </div>

      <div class="header-right">
        <!-- 批量操作按钮 -->
        <div v-if="hasSelectedFiles" class="batch-actions">
          <el-button
            type="success"
            :icon="RefreshLeft"
            :loading="restoring"
            @click="handleBatchRestore"
          >
            {{ t('trash.toolbar.batchRestore') }} ({{ selectedCount }})
          </el-button>
          <el-button
            type="danger"
            :icon="Delete"
            :loading="deleting"
            @click="handleBatchDelete"
          >
            {{ t('trash.toolbar.batchDelete') }} ({{ selectedCount }})
          </el-button>
        </div>

        <!-- 全局操作按钮 -->
        <div class="global-actions">
          <el-button
            :icon="Refresh"
            @click="handleRefresh"
            :loading="loading"
          >
            {{ t('trash.toolbar.refresh') }}
          </el-button>
          <el-button
            type="danger"
            :icon="Delete"
            :loading="emptying"
            @click="handleEmptyTrash"
            :disabled="stats.totalFiles === 0"
          >
            {{ t('trash.toolbar.emptyTrash') }}
          </el-button>
        </div>

        <!-- 排序选择 -->
        <el-select
          v-model="currentSort"
          :placeholder="t('trash.toolbar.sortBy')"
          style="width: 140px"
          @change="handleSortChange"
        >
          <el-option :label="t('trash.sort.deletedAt_desc')" value="deletedAt_desc" />
          <el-option :label="t('trash.sort.deletedAt_asc')" value="deletedAt_asc" />
          <el-option :label="t('trash.sort.originalName_desc')" value="originalName_desc" />
          <el-option :label="t('trash.sort.originalName_asc')" value="originalName_asc" />
          <el-option :label="t('trash.sort.fileSize_desc')" value="fileSize_desc" />
          <el-option :label="t('trash.sort.fileSize_asc')" value="fileSize_asc" />
        </el-select>
      </div>
    </div>

    <!-- 文件列表区域 -->
    <div class="files-container">
      <!-- 全选控制 -->
      <div v-if="trashFiles.length > 0" class="selection-bar">
        <el-checkbox
          v-model="selectAllChecked"
          :indeterminate="isIndeterminate"
        >
          {{ t('trash.toolbar.selectAll') }}
        </el-checkbox>
        <span class="selection-info">
          {{ t('trash.messages.selectedFiles', { selected: selectedCount, total: trashFiles.length }) }}
          <span v-if="selectedSize > 0">
            {{ t('trash.messages.selectedSize', { size: formatFileSize(selectedSize) }) }}
          </span>
        </span>
      </div>

      <!-- 加载状态 -->
      <div v-if="loading" class="loading-container">
        <el-skeleton :rows="8" animated />
      </div>

      <!-- 文件列表 -->
      <div v-else-if="trashFiles.length > 0" class="files-list">
        <div
          v-for="file in trashFiles"
          :key="file.id"
          class="file-item"
          :class="{ selected: isFileSelected(file) }"
          @click="handleFileClick(file)"
        >
          <!-- 选择框 -->
          <div class="file-checkbox">
            <el-checkbox
              :model-value="isFileSelected(file)"
              @change="handleFileSelect(file)"
              @click.stop
            />
          </div>

          <!-- 文件图标 -->
          <div class="file-icon">
            <el-icon size="24">
              <component :is="getFileIcon(file)" />
            </el-icon>
          </div>

          <!-- 文件信息 -->
          <div class="file-info">
            <div class="file-name">
              {{ file.originalName }}
            </div>
            <div class="file-meta">
              <span class="file-size">
                {{ file.isDirectory ? t('trash.fileList.folder') : formatFileSize(file.fileSize || 0) }}
              </span>
              <span class="deleted-time">
                {{ t('trash.fileList.deletedAt') }} {{ formatDeletedTime(file.deletedAt || '') }}
              </span>
              <span 
                v-if="isExpiringSoon(file.deletedAt || '')"
                class="expiry-warning"
              >
                {{ calculateExpiryTime(file.deletedAt || '') }}
              </span>
            </div>
          </div>

          <!-- 操作按钮 -->
          <div class="file-actions">
            <el-button
              size="small"
              type="success"
              :icon="RefreshLeft"
              @click.stop="handleRestore(file)"
            >
              {{ t('trash.fileList.restore') }}
            </el-button>
            <el-button
              size="small"
              type="danger"
              :icon="Delete"
              @click.stop="handlePermanentDelete(file)"
            >
              {{ t('trash.fileList.permanentDelete') }}
            </el-button>
          </div>
        </div>
      </div>

      <!-- 空状态 -->
      <div v-else class="empty-state">
        <el-empty :description="t('trash.messages.emptyState')">
          <template #image>
            <el-icon size="64" color="#c0c4cc">
              <Delete />
            </el-icon>
          </template>
          <el-button type="primary" @click="$router.push('/files')">
            {{ t('trash.messages.goUpload') }}
          </el-button>
        </el-empty>
      </div>

      <!-- 分页 -->
      <div v-if="!loading && pagination.totalPages > 1" class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="pagination.totalElements"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handlePageSizeChange"
          @current-change="handlePageChange"
        />
      </div>
    </div>

    <!-- 还原确认对话框 -->
    <RestoreDialog
      v-model="restoreDialogVisible"
      :files="restoreFiles"
      @confirm="handleRestoreConfirm"
    />

    <!-- 删除确认对话框 -->
    <DeleteConfirmDialog
      v-model="deleteDialogVisible"
      :files="deleteFiles"
      @confirm="handleDeleteConfirm"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Delete, RefreshLeft, Refresh, Folder, Document,
  Picture, VideoPlay, Mic, Files
} from '@element-plus/icons-vue'
import { useTrashStore } from '@/stores/trashStore'
import { storeToRefs } from 'pinia'
import type { FileInfo } from '@/types/file'
import {
  formatFileSize,
  calculateExpiryTime,
  isExpiringSoon,
  getFileTypeIcon
} from '@/api/modules/trash'
import RestoreDialog from './components/RestoreDialog.vue'
import DeleteConfirmDialog from './components/DeleteConfirmDialog.vue'

// ==================== 国际化 ====================

const { t } = useI18n()

// ==================== 状态管理 ====================

const trashStore = useTrashStore()
const {
  trashFiles,
  pagination,
  stats,
  loading,
  statsLoading,
  selectedFiles,
  restoring,
  deleting,
  emptying,
  hasSelectedFiles,
  selectedCount,
  selectedSize,
  isAllSelected,
  isIndeterminate
} = storeToRefs(trashStore)

// 从store中获取方法
const {
  isFileSelected,
  toggleFileSelection,
  toggleSelectAll,
  loadTrashFiles,
  restoreFiles: storeRestoreFiles,
  permanentDeleteFiles: storePermanentDeleteFiles,
  emptyTrash: storeEmptyTrash,
  refresh: storeRefresh
} = trashStore

// ==================== 本地状态 ====================

// 分页控制
const currentPage = ref(1)
const pageSize = ref(20)

// 排序控制
const currentSort = ref('deletedAt_desc')

// 全选状态
const selectAllChecked = computed({
  get: () => isAllSelected.value,
  set: (value: boolean) => {
    if (value) {
      // 全选
      selectedFiles.value = [...trashFiles.value]
    } else {
      // 取消全选
      selectedFiles.value = []
    }
  }
})

// 对话框状态
const restoreDialogVisible = ref(false)
const deleteDialogVisible = ref(false)
const restoreFiles = ref<FileInfo[]>([])
const deleteFiles = ref<FileInfo[]>([])

// ==================== 方法定义 ====================

/**
 * 格式化删除时间（国际化版本）
 */
const formatDeletedTime = (deletedAt: string): string => {
  const date = new Date(deletedAt)
  const now = new Date()
  const diffMs = now.getTime() - date.getTime()
  const diffMinutes = Math.floor(diffMs / (1000 * 60))
  const diffHours = Math.floor(diffMs / (1000 * 60 * 60))
  const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24))

  if (diffMinutes < 1) {
    return t('trash.time.justNow')
  } else if (diffMinutes < 60) {
    return t('trash.time.minutesAgo', { minutes: diffMinutes })
  } else if (diffHours < 24) {
    return t('trash.time.hoursAgo', { hours: diffHours })
  } else {
    return t('trash.time.daysAgo', { days: diffDays })
  }
}

/**
 * 获取文件图标组件
 */
const getFileIcon = (file: FileInfo) => {
  if (file.isDirectory) return Folder
  
  const iconType = getFileTypeIcon(file.originalName, file.isDirectory)
  const iconMap = {
    image: Picture,
    video: VideoPlay,
    audio: Mic,
    folder: Folder,
    file: Document
  }
  
  return iconMap[iconType as keyof typeof iconMap] || Document
}

/**
 * 处理文件点击
 */
const handleFileClick = (file: FileInfo) => {
  toggleFileSelection(file)
}

/**
 * 处理文件选择
 */
const handleFileSelect = (file: FileInfo) => {
  toggleFileSelection(file)
}

/**
 * 处理排序变化
 */
const handleSortChange = (value: string) => {
  const [sortBy, sortDir] = value.split('_')
  loadTrashFiles({
    page: 0,
    sortBy,
    sortDir: sortDir as 'asc' | 'desc'
  })
  currentPage.value = 1
}

/**
 * 处理分页变化
 */
const handlePageChange = (page: number) => {
  loadTrashFiles({ page: page - 1 })
}

/**
 * 处理页面大小变化
 */
const handlePageSizeChange = (size: number) => {
  pageSize.value = size
  loadTrashFiles({ page: 0, size })
  currentPage.value = 1
}

/**
 * 刷新数据
 */
const handleRefresh = () => {
  storeRefresh()
}

/**
 * 还原单个文件
 */
const handleRestore = (file: FileInfo) => {
  restoreFiles.value = [file]
  restoreDialogVisible.value = true
}

/**
 * 批量还原
 */
const handleBatchRestore = () => {
  if (!hasSelectedFiles.value) {
    ElMessage.warning(t('trash.messages.selectFiles'))
    return
  }
  restoreFiles.value = [...selectedFiles.value]
  restoreDialogVisible.value = true
}

/**
 * 确认还原
 */
const handleRestoreConfirm = async (restoreToRoot: boolean) => {
  try {
    const fileIds = restoreFiles.value.map(f => f.id)
    await storeRestoreFiles({ fileIds, restoreToRoot })

    ElMessage.success(t('trash.messages.restoreSuccess', { count: fileIds.length }))
    restoreDialogVisible.value = false
    restoreFiles.value = []

  } catch (error: any) {
    ElMessage.error(error.message || t('trash.messages.restoreFailed'))
  }
}

/**
 * 彻底删除单个文件
 */
const handlePermanentDelete = (file: FileInfo) => {
  deleteFiles.value = [file]
  deleteDialogVisible.value = true
}

/**
 * 批量彻底删除
 */
const handleBatchDelete = () => {
  if (!hasSelectedFiles.value) {
    ElMessage.warning(t('trash.messages.selectFiles'))
    return
  }
  deleteFiles.value = [...selectedFiles.value]
  deleteDialogVisible.value = true
}

/**
 * 确认彻底删除
 */
const handleDeleteConfirm = async () => {
  try {
    const fileIds = deleteFiles.value.map(f => f.id)
    await storePermanentDeleteFiles({ fileIds })

    ElMessage.success(t('trash.messages.deleteSuccess', { count: fileIds.length }))
    deleteDialogVisible.value = false
    deleteFiles.value = []

  } catch (error: any) {
    ElMessage.error(error.message || t('trash.messages.deleteFailed'))
  }
}

/**
 * 清空回收站
 */
const handleEmptyTrash = () => {
  ElMessageBox.confirm(
    t('trash.dialogs.emptyTrashPrompt', { count: stats.value.totalFiles }),
    t('trash.dialogs.emptyTrashTitle'),
    {
      confirmButtonText: t('trash.dialogs.emptyTrashConfirm'),
      cancelButtonText: t('trash.dialogs.cancel'),
      type: 'warning',
      confirmButtonClass: 'el-button--danger'
    }
  ).then(async () => {
    try {
      await storeEmptyTrash()
      ElMessage.success(t('trash.messages.emptyTrashSuccess'))
    } catch (error: any) {
      ElMessage.error(error.message || t('trash.messages.emptyTrashFailed'))
    }
  }).catch(() => {
    // 用户取消
  })
}

// ==================== 生命周期 ====================

onMounted(() => {
  storeRefresh()
})

// 监听分页变化
watch([currentPage], () => {
  if (currentPage.value !== pagination.value.page + 1) {
    loadTrashFiles({ page: currentPage.value - 1 })
  }
})
</script>

<style scoped>
.trash-view {
  height: 100%;
  display: flex;
  flex-direction: column;
  background-color: var(--el-bg-color);
}

/* 页面头部 */
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  padding: 20px 24px;
  border-bottom: 1px solid var(--el-border-color-light);
  background-color: var(--el-bg-color);
}

.header-left {
  flex: 1;
}

.title-section {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 8px;
}

.page-title {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
  color: var(--el-text-color-primary);
  display: flex;
  align-items: center;
  gap: 8px;
}

.stats-info {
  display: flex;
  gap: 16px;
  font-size: 14px;
  color: var(--el-text-color-regular);
}

.stat-item {
  display: flex;
  align-items: center;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 12px;
}

.batch-actions {
  display: flex;
  gap: 8px;
  margin-right: 12px;
  padding-right: 12px;
  border-right: 1px solid var(--el-border-color-light);
}

.global-actions {
  display: flex;
  gap: 8px;
}

/* 文件列表容器 */
.files-container {
  flex: 1;
  padding: 0 24px 24px;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

/* 选择栏 */
.selection-bar {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 12px 16px;
  background-color: var(--el-fill-color-lighter);
  border-radius: 6px;
  margin-bottom: 16px;
}

.selection-info {
  font-size: 14px;
  color: var(--el-text-color-regular);
}

/* 加载状态 */
.loading-container {
  flex: 1;
  padding: 20px;
}

/* 文件列表 */
.files-list {
  flex: 1;
  overflow-y: auto;
}

.file-item {
  display: flex;
  align-items: center;
  padding: 12px 16px;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.2s;
  border: 1px solid transparent;
}

.file-item:hover {
  background-color: var(--el-fill-color-light);
}

.file-item.selected {
  background-color: var(--el-color-primary-light-9);
  border-color: var(--el-color-primary-light-7);
}

.file-checkbox {
  margin-right: 12px;
}

.file-icon {
  margin-right: 12px;
  color: var(--el-text-color-regular);
}

.file-info {
  flex: 1;
  min-width: 0;
}

.file-name {
  font-size: 14px;
  font-weight: 500;
  color: var(--el-text-color-primary);
  margin-bottom: 4px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.file-meta {
  display: flex;
  gap: 12px;
  font-size: 12px;
  color: var(--el-text-color-regular);
}

.file-meta span {
  white-space: nowrap;
}

.expiry-warning {
  color: var(--el-color-warning) !important;
  font-weight: 500;
}

.file-actions {
  display: flex;
  gap: 8px;
  opacity: 0;
  transition: opacity 0.2s;
}

.file-item:hover .file-actions {
  opacity: 1;
}

/* 空状态 */
.empty-state {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 分页 */
.pagination-container {
  display: flex;
  justify-content: center;
  padding: 20px 0;
  border-top: 1px solid var(--el-border-color-light);
  margin-top: 20px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }

  .header-right {
    justify-content: space-between;
  }

  .batch-actions {
    margin-right: 0;
    padding-right: 0;
    border-right: none;
  }

  .file-meta {
    flex-direction: column;
    gap: 4px;
  }

  .file-actions {
    opacity: 1;
  }
}
</style>
